const jwt = require('jsonwebtoken')
const db = require('../DB/index')
const bc = require('bcryptjs')
exports.regUser = (req, res) => {
    const userinfo = req.body
    const sqlStr = 'select * from ev_userslogin where username=?'
    db.query(sqlStr, userinfo.username, (err, results) => {
        if (err) {
            return res.err(err, 2100)
        }
        if (results.length > 0) {
            return res.err('用户名被占用', 500)
        }
        userinfo.password = bc.hashSync(userinfo.password, 10)
        const sql = 'insert into ev_userslogin set ?'
        db.query(sql, { username: userinfo.username, password: userinfo.password }, (err, results) => {
            if (err) return res.send({ status: 1, message: err.message })
            if (results.affectedRows !== 1) return res.send({ status: 1, message: '注册失败' })
            res.success('注册成功！', 200)
        })
    })
}
const secre = 'zhaoying-targetportal'

exports.login = (req, res) => {
    const userinfo = req.body
    const sql = 'select * from ev_userslogin where username=?' 
    db.query(sql, userinfo.username, (err, results) => {
        if (err) return res.err(err, 500)
        if (results.length !== 1) return res.err('登录失败', 400)
        const token = jwt.sign({ username: userinfo.username }, secre, { expiresIn: '1h' })
        res.send({
            status: 200,
            message: '登录成功！',
            token: token
        })
    })
}
